import React, { useState, useEffect, useRef } from 'react';
import { 
  SearchBar, 
  List, 
  Tag, 
  Empty,
  Button,
  Toast,
  Loading
} from 'antd-mobile';
import { 
  ArrowLeftOutlined, 
  SearchOutlined, 
  ClockCircleOutlined, 
  StarOutlined,
  HistoryOutlined,
  FireOutlined,
  DeleteOutlined,
  MedicineBoxOutlined,
  RightOutlined 
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import './Search.css';

// 模拟中医理疗项目数据
const therapyItems = [
  {
    id: 1,
    name: "肩颈推拿调理",
    desc: "采用揉、捏、按、推手法，疏通肩井、天宗、风池穴位，缓解久坐肌肉僵硬",
    price: 128,
    originalPrice: 168,
    duration: "45分钟",
    rating: 4.8,
    sales: 328,
    tag: "热门",
    image: "https://picsum.photos/id/177/300/300",
    acupoints: ["肩井穴", "天宗穴", "风池穴"],
    suitable: "办公室久坐人群、肩颈酸痛者"
  },
  {
    id: 2,
    name: "腰椎艾灸养护",
    desc: "温灸肾俞、大肠俞、委中穴位，温经散寒，改善腰椎劳损引起的疼痛",
    price: 158,
    originalPrice: 198,
    duration: "60分钟",
    rating: 4.9,
    sales: 256,
    tag: "推荐",
    image: "https://picsum.photos/id/237/300/300",
    acupoints: ["肾俞穴", "大肠俞穴", "委中穴"],
    suitable: "腰椎间盘突出、久坐腰痛者"
  },
  {
    id: 3,
    name: "全身经络刮痧",
    desc: "沿膀胱经、督脉走向刮痧，促进气血运行，排出体内湿寒",
    price: 198,
    originalPrice: 238,
    duration: "90分钟",
    rating: 4.7,
    sales: 189,
    tag: "经典",
    image: "https://picsum.photos/id/287/300/300",
    acupoints: ["膀胱经", "督脉", "足三里"],
    suitable: "湿气重、疲劳乏力人群"
  },
  {
    id: 4,
    name: "艾灸养生疗法",
    desc: "精选陈年艾草，针对大椎、命门、足三里穴位，驱寒除湿调理体质",
    price: 138,
    originalPrice: 158,
    duration: "50分钟",
    rating: 4.6,
    sales: 156,
    tag: "养生",
    image: "https://picsum.photos/id/184/300/300",
    acupoints: ["大椎穴", "命门穴", "足三里穴"],
    suitable: "体质虚寒、免疫力低下者"
  },
  {
    id: 5,
    name: "足部反射区按摩",
    desc: "刺激足底肾、肝、脾反射区，调节脏腑功能，改善睡眠质量",
    price: 88,
    originalPrice: 108,
    duration: "30分钟",
    rating: 4.5,
    sales: 210,
    tag: "放松",
    image: "https://picsum.photos/id/187/300/300",
    acupoints: ["涌泉穴", "太冲穴", "太白穴"],
    suitable: "失眠多梦、足部疲劳人群"
  }
];

// 热门搜索标签
const hotSearches = [
  "推拿", "艾灸", "肩颈", "腰椎", "养生", 
  "经络疏通", "拔罐", "刮痧", "穴位按摩", "办公室调理"
];

// 搜索建议
const searchSuggestions = [
  "肩颈推拿按摩", "艾灸调理方法", "腰椎刮痧穴位", 
  "办公室养生操", "中医养生茶配方", "穴位按摩技巧"
];

const Search = () => {
  const navigate = useNavigate();
  const [searchText, setSearchText] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [showResults, setShowResults] = useState(false);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [searchHistory, setSearchHistory] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const searchInputRef = useRef(null);
  const suggestContainerRef = useRef(null);

  // 从本地存储加载搜索历史
  useEffect(() => {
    const savedHistory = localStorage.getItem('herbalSearchHistory');
    if (savedHistory) {
      setSearchHistory(JSON.parse(savedHistory));
    }

    // 点击页面空白处隐藏搜索建议
    const handleClickOutside = (e) => {
      if (searchInputRef.current && !searchInputRef.current.contains(e.target) &&
          suggestContainerRef.current && !suggestContainerRef.current.contains(e.target)) {
        setShowSuggestions(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);
  
  // 保存搜索历史到本地存储
  useEffect(() => {
    if (searchHistory.length > 0) {
      localStorage.setItem('herbalSearchHistory', JSON.stringify(searchHistory));
    }
  }, [searchHistory]);
  
  // 处理搜索输入变化
  const handleSearchChange = (value) => {
    setSearchText(value);
    
    if (value.trim() === '') {
      setShowResults(false);
      setShowSuggestions(false);
      return;
    }

    // 显示搜索建议
    setShowSuggestions(true);
  };
  
  // 执行搜索
  const handleSearch = (value = searchText) => {
    const query = value.trim();
    if (!query) return;

    setIsLoading(true);
    setShowSuggestions(false);
    
    // 模拟搜索请求
    setTimeout(() => {
      const results = therapyItems.filter(item => 
        item.name.includes(query) || 
        item.desc.includes(query) ||
        item.tag.includes(query) ||
        item.acupoints.some(acupoint => acupoint.includes(query))
      );
      
      setSearchResults(results);
      setShowResults(true);
      setIsLoading(false);
      
      // 添加到搜索历史（去重+限制10条）
      if (!searchHistory.includes(query)) {
        const newHistory = [query, ...searchHistory].slice(0, 10);
        setSearchHistory(newHistory);
      }
    }, 500);
  };
  
  // 清除搜索历史
  const clearHistory = () => {
    setSearchHistory([]);
    localStorage.removeItem('herbalSearchHistory');
    Toast.show('搜索历史已清除');
  };
  
  // 从历史记录/热门标签/搜索建议搜索
  const searchFromSource = (text) => {
    setSearchText(text);
    handleSearch(text);
  };
  
  // 删除单个历史记录
  const deleteHistoryItem = (text, e) => {
    e.stopPropagation();
    const newHistory = searchHistory.filter(item => item !== text);
    setSearchHistory(newHistory);
    Toast.show('已删除该历史记录');
  };
  
  // 查看项目详情
  const viewItemDetail = (item) => {
    navigate(`/therapy/${item.id}`, { state: { item } });
  };
  
  // 渲染搜索建议列表
  const renderSuggestions = () => {
    if (!showSuggestions || !searchText.trim()) return null;
    
    const filteredSuggestions = searchSuggestions.filter(suggest => 
      suggest.includes(searchText.trim())
    );
    
    return (
      <div 
        ref={suggestContainerRef}
        className="search-suggest-container"
      >
        <List className="suggest-list">
          {filteredSuggestions.map((suggest, index) => (
            <List.Item 
              key={index}
              className="suggest-item"
              onClick={() => searchFromSource(suggest)}
            >
              <MedicineBoxOutlined className="suggest-icon" />
              <span className="suggest-text">{suggest}</span>
            </List.Item>
          ))}
        </List>
      </div>
    );
  };

  return (
    <div className="herbal-search-page">
      {/* 顶部导航栏 */}
      <header className="search-header">
         <i class="fa fa-arrow-left"  style={{ color: '#8B5A2B', fontSize: '20px',cursor:'pointer' }} onClick={() => window.history.back()}></i>
     
        <h1 className="search-title">搜索</h1>
        <div
          variant="text"
          className="user-btn">
         
        </div>
      </header>

      {/* 搜索框区域 */}
      <div className="search-container" ref={searchInputRef}>
        <SearchBar
          className="herbal-search-bar"
          value={searchText}
          onChange={handleSearchChange}
          onSearch={handleSearch}
          placeholder="例如：肩颈推拿、艾灸调理、腰痛穴位..."
          leftIcon={<MedicineBoxOutlined className="search-bar-icon" />}
          onClear={() => {
            setSearchText('');
            setShowResults(false);
            setShowSuggestions(false);
          }}
          showCancelButton={false}
        />
        
        {/* 搜索建议列表 */}
        {renderSuggestions()}
      </div>
      
      {/* 搜索内容区域 */}
      <div className="search-content">
        {/* 搜索结果展示 */}
        {showResults ? (
          <div className="search-results">
            {isLoading ? (
              <div className="loading-container">
                <Loading size="large" color="#8B5A2B" />
                <p className="loading-text">正在搜索理疗项目...</p>
              </div>
            ) : (
              <>
                <div className="results-header">
                  找到 {searchResults.length} 个相关中医理疗项目
                </div>
                
                {searchResults.length > 0 ? (
                  <List className="results-list">
                    {searchResults.map(item => (
                      <List.Item 
                        key={item.id}
                        className="result-item"
                        onClick={() => viewItemDetail(item)}
                      >
                        <div className="result-image">
                          <img 
                            src={item.image} 
                            alt={item.name}
                            onError={(e) => e.target.src = "https://picsum.photos/id/1005/300/300"}
                            className="item-image"
                          />
                        </div>
                        
                        <div className="result-info">
                          <div className="result-name-row">
                            <h3 className="result-name">{item.name}</h3>
                            <Tag className={`result-tag tag-${item.tag}`}>
                              {item.tag}
                            </Tag>
                          </div>
                          
                          <p className="result-desc">{item.desc}</p>
                          
                          <div className="result-meta">
                            <div className="price-info">
                              <span className="current-price">¥{item.price}</span>
                              <span className="original-price">¥{item.originalPrice}</span>
                            </div>
                            
                            <div className="duration-info">
                              <ClockCircleOutlined className="meta-icon" />
                              <span>{item.duration}</span>
                            </div>
                            
                            <div className="rating-info">
                              <StarOutlined className="star-icon" />
                              <span>{item.rating}</span>
                            </div>
                            
                          </div>
                        </div>
                      </List.Item>
                    ))}
                  </List>
                ) : (
                  <div className="no-results">
                    <Empty 
                      description={
                        <div className="no-results-text">
                          未找到相关中医理疗项目
                        </div>
                      }
                      image={<MedicineBoxOutlined style={{ fontSize: '48px', color: '#8B5A2B' }} />}
                    />
                    <Button 
                      className="reset-btn"
                      variant="text"
                      onClick={() => {
                        setSearchText('');
                        setShowResults(false);
                      }}
                    >
                      清除搜索条件
                    </Button>
                  </div>
                )}

                {/* 加载更多按钮 */}
                {searchResults.length > 0 && (
                  <Button 
                    className="load-more-btn"
                    variant="text"
                    onClick={() => {
                      // 模拟加载更多
                      setIsLoading(true);
                      setTimeout(() => {
                        const randomIndex = Math.floor(Math.random() * therapyItems.length);
                        const newItem = therapyItems[randomIndex];
                        if (!searchResults.some(item => item.id === newItem.id)) {
                          setSearchResults([...searchResults, newItem]);
                        }
                        setIsLoading(false);
                      }, 800);
                    }}
                    loading={isLoading}
                  >
                    加载更多理疗项目
                  </Button>
                )}
              </>
            )}
          </div>
        ) : (
          // 搜索建议区域
          <div className="search-suggestions">
            {/* 历史搜索 */}
            {searchHistory.length > 0 && (
              <div className="search-section history-section">
                <div className="section-header">
                  <div className="section-title">
                    
                    搜索历史
                  </div>
                  <div 
                    variant="text" 
                    className="clear-history-btn"
                    onClick={clearHistory}
                  >
                    <DeleteOutlined className="delete-icon" />
                    清除
                  </div>
                </div>
                
                <div className="history-tags">
                  {searchHistory.map((item, index) => (
                    <div 
                      key={index} 
                      className="history-tag"
                      onClick={() => searchFromSource(item)}
                    >
                      <span className="history-tag-text">{item}</span>
                      <Button 
                        variant="text" 
                        className="tag-delete-btn"
                        onClick={(e) => deleteHistoryItem(item, e)}
                      >
                        <DeleteOutlined className="tag-delete-icon" />
                      </Button>
                    </div>
                  ))}
                </div>
              </div>
            )}
            
            {/* 热门搜索 */}
            <div className="search-section hot-section">
              <div className="section-header">
                <div className="section-title">
                  热门搜索
                </div>
              </div>
              
              <div className="hot-tags">
                {hotSearches.map((tag, index) => (
                  <Tag 
                    key={index}
                    className="hot-tag"
                    onClick={() => searchFromSource(tag)}
                  >
                    {tag}
                  </Tag>
                ))}
              </div>
            </div>
            
            {/* 推荐理疗项目 */}
            <div className="search-section recommend-section">
              <div className="section-header">
                <div className="section-title">
                  推荐理疗项目
                </div>
              </div>
              
              <List className="recommend-list">
                {therapyItems.slice(0, 3).map(item => (
                  <List.Item 
                    key={item.id}
                    className="recommend-item"
                    onClick={() => viewItemDetail(item)}
                  >
                    <div className="recommend-item-content">
                      <MedicineBoxOutlined className="recommend-icon" />
                      <span className="recommend-text">{item.name}</span>
                      <Tag className={`recommend-tag tag-${item.tag}`}>
                        {item.tag}
                      </Tag>
                    </div>
                  </List.Item>
                ))}
              </List>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Search;
